package com.by.gateway.config;

import com.by.gateway.service.GatewayForwardService;
import com.by.gateway.service.EndpointService;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;

public class GatewayChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final GatewayForwardService gatewayForwardService;

    public GatewayChannelInitializer(GatewayForwardService gatewayForwardService) {
        this.gatewayForwardService = gatewayForwardService;
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        // HTTP 编解码器
        pipeline.addLast(new HttpServerCodec());
        // 将多个 HTTP 消息片段聚合成一个完整的 HttpObject，最大 1MB
        pipeline.addLast(new HttpObjectAggregator(1048576));
        // 自定义业务逻辑处理器
        pipeline.addLast(new HttpRequestHandler(gatewayForwardService));
        // 注意：这里我们只传递了 GatewayForwardService，因为 EndpointService 已经通过 @Autowired 注入到了 GatewayForwardService 中。
        // 这是正确的依赖传递方式。
    }
}